﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using CaiyinSoft.NetGather.Protocol;
using CaiyinSoft.NetGather.NetGatherLib;
using CaiyinSoft.NetGather.NetGatherUtility;
using CaiyinSoft.NetGather.NetGatherLib.Filter;
using CaiyinSoft.NetGather.NetGatherLib.Analyzer;
using CaiyinSoft.NetGather.NetGatherLib.Publisher;
using CaiyinSoft.NetGather.NetGatherLib.URLSource;
using CaiyinSoft.NetGather.NetGatherLib.Filter.Process;
using CaiyinSoft.NetGather.NetGatherLib.Filter.Special;
using CaiyinSoft.NetGather.NetGatherLib.Filter.Generate;
using ICSharpCode.TextEditor;
using ICSharpCode.TextEditor.Document;

namespace CaiyinSoft.NetGather.NetGather
{
    public partial class FrmTaskEditer : Form
    {

        private string _formTitle = "任务";
        private string _testHTML = null;
        public FrmTaskEditer()
        {
            InitializeComponent();
            txtTestHTML .Document.HighlightingStrategy = HighlightingStrategyFactory.CreateHighlightingStrategy("HTML");
        }

        private Task _task;
        public Task Task
        {
            get
            {
                return _task;
            }
            set
            {
                _task = value;
                if (value != null)
                {
                    this.Text = string.Format("{0} - {1}", _formTitle, Task.TaskName);
                    txtTaskName.Text = Task.TaskName;
                    //labGUID.Text = Task.TaskID;
                    ShowTab1();
                    ShowTab2();
                    ShowTab3();
                    ShowTab4();
                    ShowTab5();
                }
            }
        }

        private TaskListItem _taskListItem;
        public TaskListItem TaskListItem
        {
            get
            {
                return _taskListItem;
            }
            set
            {
                _taskListItem = value;
                string tp = value.GetFullPath();

                if (System.IO.File.Exists(tp))
                {
                    CaiyinSoft.NetGather.NetGatherLib.Task task = CaiyinSoft.NetGather.NetGatherLib.Task.Read(tp);
                    this.labGUID.Text = tp;
                    this.Task = task;
                }
                else
                {
                    this.labGUID.Text = "";
                    Task task = new Task();
                    this.Task = task;
                }
            }
        }

        private void BindAddItemEvent()
        {

        }
        /// <summary>
        /// 数据源
        /// </summary>
        private void ShowTab1()
        {
            if (Task.URLSource is TextURLSource)
            {
                cmbSource.SelectedIndex = 0;
            }
            else if (Task.URLSource is SQLURLSource)
            {
                cmbSource.SelectedIndex = 1;
            }

            panSource.Controls.Clear();
            if (Task.URLSource != null)
            {
                InnerFormBase frm = Task.URLSource.GetEditForm();
                if (frm != null)
                {
                    frm.Left = 0;
                    frm.Top = 0;
                    frm.Width = panSource.Width;
                    frm.Height = panSource.Height;
                    frm.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Bottom;
                    panSource.Controls.Add(frm);
                }
            }

        }

        /// <summary>
        /// 采集基本设置
        /// </summary>
        private void ShowTab2()
        {
            cmbEncoding.Text = Task.Converter.Encoding;
            numInterval.Value = Task.Converter.Interval;
            cmbIsList.SelectedIndex = Task.Converter.ListResult == true ? 1 : 0;
        }

        /// <summary>
        /// 采集规则
        /// </summary>
        private void ShowTab3()
        {
            TreeNode Content = new TreeNode("内容");
            TreeNode NextPage = new TreeNode("下一页");
            trvFilters.Nodes.Add(Content);
            trvFilters.Nodes.Add(NextPage);

            Content.Tag = Task.Converter.HTMLAnalyzer;
            NextPage.Tag = Task.Converter.HTMLAnalyzer;

            foreach (var filter in Task.Converter.HTMLAnalyzer.HTMLFilters)
            {
                AddChild(Content, filter);
            }

            AddChild(NextPage, Task.Converter.HTMLAnalyzer.NextHTMLFilter);
        }

        private void AddChild(TreeNode parentNode, IHTMLFilter Filter)
        {
            if (Filter == null) return;
            TreeNode node = new TreeNode(Filter.FilterCaption);
            //if (!CaiyinSoft.NetGather.NetGatherUtility.Utility.IsGUID(Filter.OutputKey))
            //{
            //    node.Text = Filter.OutputKey;
            //}
            node.Tag = Filter;
            parentNode.Nodes.Add(node);

            foreach (var filter in Filter.ChildFilters)
            {
                AddChild(node, filter);
            }
        }

        private void getChild(TreeNode parentNode, IHTMLFilter Filter)
        {
            foreach (TreeNode node in parentNode.Nodes)
            {
                IHTMLFilter f = node.Tag as IHTMLFilter;
                f.ChildFilters.Clear();
                Filter.AddChildFilter(f);
                getChild(node, f);
            }
        }


        /// <summary>
        /// 发布
        /// </summary>
        private void ShowTab4()
        {
            if (Task.HTMLPubliser is SQLHTMLPublisher)
            {
                cmbPublisher.SelectedIndex = 0;
            }
            else if (Task.HTMLPubliser is TextHTMLPublisher)
            {
                cmbPublisher.SelectedIndex = 1;
            }

            panPublisher.Controls.Clear();
            if (Task.HTMLPubliser != null)
            {
                InnerFormBase frm = Task.HTMLPubliser.GetEditForm();
                if (frm != null)
                {
                    frm.Left = 0;
                    frm.Top = 0;
                    frm.Width = panPublisher.Width;
                    frm.Height = panPublisher.Height;
                    frm.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Bottom;
                    panPublisher.Controls.Add(frm);
                }
            }

        }

        /// <summary>
        /// 测试数据
        /// </summary>
        private void ShowTab5()
        {

            if (this.Task.TestType == 1)
            {
                radTestURL.Checked = true;
            }
            else if (this.Task.TestType == 2)
            {
                radTestHTML.Checked = true;
            }
            else
            {
                radTestFromDataSource.Checked = true;
            }

            txtTestURL.Text = this.Task.TestURL;
            txtTestHTML.Text = this.Task.TestHTML;
        }

        private void FrmTaskEditer_Load(object sender, EventArgs e)
        {
            tabControl1.SelectedIndex = 0;

            //TaskListItem tlItem = new TaskListItem();
            //tlItem.SavePath = "c:\\aaa.con";
            //this.TaskListItem = tlItem;

            //CaiyinSoft.NetGather.NetGatherLib.Task task = CaiyinSoft.NetGather.NetGatherLib.Task.Read("c:\\aaa.con");
            //this.Task = task;
        }

        private void trvFilters_AfterSelect(object sender, TreeViewEventArgs e)
        {

            if (panFilters.Controls.Count > 0)
            {
                InnerFormBase frm = (InnerFormBase)panFilters.Controls[0];
                frm.SaveInfo();
            }

            panFilters.Controls.Clear();
            if (e.Node.Tag != null)
            {
                IHTMLFilter filter = e.Node.Tag as IHTMLFilter;
                ShowFilterInnerForm(filter);
            }
        }


        private void tbTools_CheckedChanged(object sender, EventArgs e)
        {
            //toolStrip2.Tag = ((ToolStripButton)sender).Tag;
            foreach (ToolStripButton item in toolStrip2.Items)
            {
                if (item.Tag == toolStrip2.Tag)
                    item.Checked = true;
                else
                    item.Checked = false;
            }

            if (panFilters.Controls.Count > 0)
            {
                InnerFormBase frm = (InnerFormBase)panFilters.Controls[0];
                frm.SaveInfo();
            }

            panFilters.Controls.Clear();
            TreeNode node = trvFilters.SelectedNode;
            if (node.Tag != null)
            {
                IHTMLFilter filter = node.Tag as IHTMLFilter;
                ShowFilterInnerForm(filter);
            }
        }

        /// <summary>
        /// 确保_testHTML的内容
        /// </summary>
        private void ensureTestHTML()
        {
            if (string.IsNullOrEmpty(_testHTML))
            {
                if (radTestFromDataSource.Checked)
                {
                    if (this.Task.URLSource == null) return;
                    if (this.Task.Converter == null) return;

                    List<URLItem> urls = this.Task.URLSource.GetURLCollection();
                    if (urls.Count > 0)
                    {
                        this.Task.Converter.SetInputURL(urls[0].URL);
                        _testHTML = this.Task.Converter.GetTestHTML();
                    }
                }
                else if (radTestURL.Checked)
                {
                    this.Task.Converter.SetInputURL(txtTestURL.Text);
                    _testHTML = this.Task.Converter.GetTestHTML();
                }
                else if (radTestHTML .Checked)
                {
                    this.Task.Converter.SetInputURL(""); 
                    _testHTML = txtTestHTML.Text;
                } 
            }
        }

        private void ShowFilterInnerForm(IHTMLFilter filter)
        {
            int type = Convert.ToInt32(toolStrip2.Tag.ToString());
            if (filter != null)
            {
                InnerFormBase frm = null;
                switch (type)
                {
                    case 0:
                        frm = filter.GetEditForm();
                        break;
                    case 1:
                        ensureTestHTML();
                        frm = filter.GetFilterResultForm(_testHTML);
                        break;
                    case 2:
                        ensureTestHTML();
                        frm = filter.GetHTMLSourceForm(_testHTML);
                        break;
                    case 3:
                        ensureTestHTML();
                        frm = filter.GetDomSourceForm(_testHTML);
                        break;
                    case 4:
                        ensureTestHTML();
                        frm = filter.GetRegexTestForm(_testHTML);
                        break;
                    default:
                        frm = filter.GetEditForm();
                        break;
                }


                if (frm != null)
                {
                    frm.Left = 0;
                    frm.Top = 0;
                    frm.Width = panFilters.Width;
                    frm.Height = panFilters.Height;
                    frm.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Bottom;
                    panFilters.Controls.Add(frm);
                }
            }

        }

        private void ta_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            IHTMLFilter filter = null;
            string name = e.ClickedItem.Name.ToString();
            if (name.CompareTo("ta01") == 0)
            {
                filter = new CaiyinSoft.NetGather.NetGatherLib.Filter.XPathHTMLAnalyze();
            }
            else if (name.CompareTo("ta02") == 0)
            {
                filter = new CaiyinSoft.NetGather.NetGatherLib.Filter.Special.TitleHTMLAnalyze();
            }
            else if (name.CompareTo("ta03") == 0)
            {
                filter = new CaiyinSoft.NetGather.NetGatherLib.Filter.Special.KeywordsHTMLAnalyze();
            }
            else if (name.CompareTo("ta04") == 0)
            {
                filter = new CaiyinSoft.NetGather.NetGatherLib.Filter.Special.DescriptionHTMLAnalyze();
            }
            else if (name.CompareTo("ta05") == 0)
            {
                filter = new CaiyinSoft.NetGather.NetGatherLib.Filter.Special.ImgSrcHTMLAnalyze();
            }
            else if (name.CompareTo("ta06") == 0)
            {
                filter = new CaiyinSoft.NetGather.NetGatherLib.Filter.Special.LinkHrefHTMLAnalyze();
            }
            else if (name.CompareTo("ta07") == 0)
            {
                filter = new CaiyinSoft.NetGather.NetGatherLib.Filter.Special.AttributeHTMLAnalyze();
            }
            _AddFilter(filter);
        }

        private void tb_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            IHTMLFilter filter = null;
            string name = e.ClickedItem.Name.ToString();
            if (name.CompareTo("tb01") == 0)
            {
                filter = new CaiyinSoft.NetGather.NetGatherLib.Filter.RegexHTMLAnalyze();
            }
            else if (name.CompareTo("tb02") == 0)
            {
                filter = new CaiyinSoft.NetGather.NetGatherLib.Filter.Special.ImgSrcRegexHTMLAnalyze();
            }
            else if (name.CompareTo("tb03") == 0)
            {
                filter = new CaiyinSoft.NetGather.NetGatherLib.Filter.Special.NextPageRegexHTMLAnalyze();
            }
            _AddFilter(filter);
        }

        private void tc_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            IHTMLFilter filter = null;
            string name = e.ClickedItem.Name.ToString();
            if (name.CompareTo("tc01") == 0)
            {
                filter = new CaiyinSoft.NetGather.NetGatherLib.Filter.Generate.GUIDHTMLAnalyze();
            }
            else if (name.CompareTo("tc02") == 0)
            {
                filter = new CaiyinSoft.NetGather.NetGatherLib.Filter.Process.SimpleReplaceHTMLAnalyze();
            }
            else if (name.CompareTo("tc03") == 0)
            {
                filter = new CaiyinSoft.NetGather.NetGatherLib.Filter.Process.SubStringHTMLAnalyze();
            }
            else if (name.CompareTo("tc04") == 0)
            {
                filter = new CaiyinSoft.NetGather.NetGatherLib.Filter.Process.FormatHTMLAnalyze();
            }
            else if (name.CompareTo("tc05") == 0)
            {
                filter = new CaiyinSoft.NetGather.NetGatherLib.Filter.Process.HTMLInnetTextHTMLAnalyze();
            }
            else if (name.CompareTo("tc06") == 0)
            {
                filter = new CaiyinSoft.NetGather.NetGatherLib.Filter.Process.FileDownloadHTMLFilter();
            }
            else if (name.CompareTo("tc07") == 0)
            {
                filter = new CaiyinSoft.NetGather.NetGatherLib.Filter.Process.HTMLSelfOnlyInnerTextHTMLFilter();
            }
            else if (name.CompareTo("tc999") == 0)
            {
                filter = new CaiyinSoft.NetGather.NetGatherLib.Filter.Process.CSharpCodeHTMLFilter();
            }

            _AddFilter(filter);
        }
        private void _AddFilter(IHTMLFilter filter)
        {
            if (filter == null) return;
            if (trvFilters.SelectedNode == null) return;
            //if (trvFilters.SelectedNode.Level ==0 ) return;

            IHTMLFilter parentFilter = trvFilters.SelectedNode.Tag as IHTMLFilter;
            if (parentFilter != null)
            {
                parentFilter.AddChildFilter(filter);
            }
            else
            {
                this.Task.Converter.HTMLAnalyzer.AddFilter(filter);
            }

            TreeNode node = new TreeNode(filter.FilterCaption);
            node.Tag = filter;
            trvFilters.SelectedNode.Nodes.Add(node);

        }

        private void tbDel_Click(object sender, EventArgs e)
        {
            if (trvFilters.SelectedNode == null) return;
            if (trvFilters.SelectedNode.Level == 0) return;
            TreeNode node = trvFilters.SelectedNode;
            TreeNode parentNode = node.Parent;
            parentNode.Nodes.Remove(node);
            trvFilters.SelectedNode = parentNode;
        }

        private void tbCopy_Click(object sender, EventArgs e)
        {

        }

        private void tbCut_Click(object sender, EventArgs e)
        {

        }

        private void tbPaste_Click(object sender, EventArgs e)
        {

        }

        private void trvFilters_BeforeSelect(object sender, TreeViewCancelEventArgs e)
        {

        }

        private void txtTaskName_TextChanged(object sender, EventArgs e)
        {
            if (txtTaskName.Text.Length > 0)
                this.Text = string.Format("{0} - {1}", _formTitle, txtTaskName.Text);
            else
                this.Text = "";

        }

        private void btClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btApply_Click(object sender, EventArgs e)
        {
            try
            {
                saveTask();
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        private bool saveTask()
        {
            if (_task == null)
                _task = new Task();

            //if (string.IsNullOrEmpty(Task.TaskID))
            //{
            //    Task.TaskID = Guid.NewGuid().ToString();
            //}

            //基本
            Task.TaskName = txtTaskName.Text;
            //数据源
            if (panSource.Controls.Count > 0)
            {
                InnerFormBase frm = (InnerFormBase)panSource.Controls[0];
                frm.SaveInfo();
            }
            //采集信息
            Task.Converter.Encoding = cmbEncoding.Text;
            Task.Converter.Interval = Convert.ToInt32(numInterval.Value);
            Task.Converter.ListResult = cmbIsList.SelectedIndex == 0 ? false : true;
            //测试数据
            if (radTestURL.Checked == true)
                Task.TestType = 1;
            else if (radTestHTML.Checked == true)
                Task.TestType = 2;
            else
                Task.TestType = 0;

            Task.TestURL = txtTestURL.Text;
            Task.TestHTML = txtTestHTML.Text;

            //规则
            if (panFilters.Controls.Count > 0)
            {
                InnerFormBase frm = (InnerFormBase)panFilters.Controls[0];
                frm.SaveInfo();
            }

            TreeNode Content = trvFilters.Nodes[0];
            TreeNode NextPage = trvFilters.Nodes[1];
            Task.Converter.HTMLAnalyzer.HTMLFilters.Clear();
            foreach (TreeNode node in Content.Nodes)
            {
                IHTMLFilter f = node.Tag as IHTMLFilter;
                f.ChildFilters.Clear();
                Task.Converter.HTMLAnalyzer.AddFilter(f);
                getChild(node, f);
            }

            foreach (TreeNode node in NextPage.Nodes)
            {
                IHTMLFilter f = node.Tag as IHTMLFilter;
                Task.Converter.HTMLAnalyzer.NextHTMLFilter = f;
                f.ChildFilters.Clear();
                getChild(node, f);
                break;
            }
            //发布
            if (panPublisher.Controls.Count > 0)
            {
                InnerFormBase frm = (InnerFormBase)panPublisher.Controls[0];
                frm.SaveInfo();
            }


            TaskListItem.TaskName = this.Task.TaskName;
            string savePath = TaskListItem.GetFullPath();
            bool bl = CaiyinSoft.NetGather.NetGatherLib.Task.Save(savePath, this.Task, string.IsNullOrEmpty(TaskListItem.TaskID));

            if (string.IsNullOrEmpty(TaskListItem.TaskID) || TaskListItem.TaskID.Length == 0)
            {
                TaskListItem.TaskID = Guid.NewGuid().ToString();
            }
            //this.Task.TaskID = TaskListItem.TaskID;
            TaskListItem.TaskName = this.Task.TaskName;
            TaskListItem.SavePath = savePath;

            return true;
        }

        private void btCreateUrlSource_Click(object sender, EventArgs e)
        {
            IURLSource newURLSource = null, tchk = null;

            switch (cmbSource.SelectedIndex)
            {
                case 0:
                    tchk = this.Task.URLSource as TextURLSource;
                    if (tchk == null)
                        newURLSource = new TextURLSource();
                    break;
                case 1:
                    tchk = this.Task.URLSource as SQLURLSource;
                    if (tchk == null)
                        newURLSource = new SQLURLSource();
                    break;
                default:
                    break;
            }

            if (newURLSource != null)
            {
                this.Task.URLSource = newURLSource;
                panSource.Controls.Clear();
                panSource.Controls.Add(this.Task.URLSource.GetEditForm());
            }


        }

        private void btCreateUrlPublicsher_Click(object sender, EventArgs e)
        {
            IHTMLPublisher newHtmlPublisher = null, tchk = null;

            switch (cmbPublisher.SelectedIndex)
            {
                case 0:
                    tchk = this.Task.HTMLPubliser as SQLHTMLPublisher;
                    if (tchk == null)
                        newHtmlPublisher = new SQLHTMLPublisher();
                    break;
                case 1:
                    tchk = this.Task.HTMLPubliser as TextHTMLPublisher;
                    if (tchk == null)
                        newHtmlPublisher = new TextHTMLPublisher();
                    break;
                default:
                    break;
            }

            if (newHtmlPublisher != null)
            {
                this.Task.HTMLPubliser = newHtmlPublisher;
                panPublisher.Controls.Clear();
                panPublisher.Controls.Add(this.Task.HTMLPubliser.GetEditForm());
            }
        }

        private void tbTools_Click(object sender, EventArgs e)
        {
            ToolStripButton tb = sender as ToolStripButton;
            if (tb != null)
            {
                toolStrip2.Tag = tb.Tag;
                tb.Checked = true;
            }
        }

        private void radTest_CheckedChanged(object sender, EventArgs e)
        {
            _testHTML = null;
        }

        private void FrmTaskEditer_SizeChanged(object sender, EventArgs e)
        {
           
        }

    }
}
